package com.wmm.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;
import java.util.Map;

/**
 * JSON转化和校验工具
 * */
public class JSONUtils {

	public static <T> String convertWXResultJson(List<T> list, int count) {
		JSONArray json = new JSONArray();
		json.addAll(list);
		String str = "";
		if (list != null && list.size() > 0) {
			str = "{\"total\":\"" + count + "\",\"data\":" + json + "}";
		} else {
			str = "{\"total\":\"" + count + "\",\"data\":[]}";
		}
		return str;
	}

	/**
	 * 根据参数key数组验证非空,&&关系
	 */
	public static boolean validateByKeys(JSONObject jsonObject, String... strings) {
		if (strings.length > 0) {
			for(String string : strings) {
				if (StringUtils.isNull(jsonObject.get(string)))
					return false;
				else {
					if (isJSONValid(jsonObject.getString(string))) {
						 for (Map.Entry<String, Object> entry : JSONObject.parseObject(jsonObject.getString(string)).entrySet()) {
							 if(StringUtils.isNull(entry.getValue())) return false;
				         }
					}
				}
			}
				
			return true;
		}
		return false;
	}
	

	/**
	 * 根据参数key数组验证非空,||关系
	 */
	public static boolean validateByKeysAllNull(JSONObject jsonObject, String[] strings) {
		int count = 0;
		if (strings.length > 0) {
			for (int i = 0; i < strings.length; i++) {
				if (StringUtils.isNull(jsonObject.get(strings[i])))
					count++;
			}
		}
		return count == strings.length ? false : true;
	}
	
	/**
	 * 验证字符串是否为json格式
	 * */
	public final static boolean isJSONValid(String test) {
		try {
			JSONObject.parseObject(test);
		} catch (Exception ex) {
			return false;
		}
		return true;
	}

}
